//
//  WQAccountViewModel.swift
//  sanwuWeibo
//
//  Created by 王先强 on 15/12/9.
//  Copyright © 2015年 王先强. All rights reserved.
//

import UIKit

class WQAccountViewModel {
    
    
    static let sharedAccount = WQAccountViewModel()
    
    //解档存储用户信息,直接加载沙河
    var account:WQAccount?
    
//{
//    var account:WQAccount? = (NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? WQAccount)
//    if !isExpired {account = nil}
//    return account
//}
    var profileIconUrl: NSURL {
        return NSURL(string: account?.avatar_large ?? "")!
    }


    
    //是否登陆标记
    var isLogin: Bool {
        return account?.access_token != nil && !isExpired
    }
    //直接沙盒加载account，对属性初始化
    private init() {
        account = (NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? WQAccount)
        if isExpired {
            print("已经过期")
            account = nil
        }
    }
    
    //授权日期是否过期
    private var isExpired: Bool {
        if account?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            return false
        }
        return true
    }
    //账户存储路径
    private var accountPath: String {
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        return (path as NSString).stringByAppendingPathComponent("account.plist")
    }

  
}

extension WQAccountViewModel {
    func loadAccessTokenAndUserInfo(code: String, finishedCallBack:((success: AnyObject?, failure: NSError?) -> ())) {
        
        WQNetTool.shareTool.loadAccessToken(code) { (success, failure) -> () in
            
            //判断回调的闭包中网络访问是否出错
            if failure != nil {
                let error:NSError = NSError(domain: "加载accsToken错误", code: -1001, userInfo: nil)
                finishedCallBack(success: nil, failure: error)
                return
            }
            
            //判断返回的数据是否为字典
            guard let dict = success as? [String: AnyObject] else {
                let error:NSError = NSError(domain: "返回的数据不是为字典", code: -1002, userInfo: nil)
                finishedCallBack(success: nil, failure: error)
                return
            }
            
            //确定字典数据正常，进行字典转模型
            self.account = WQAccount(dict: dict)
            
            /// 利用获得的accssToken进一步加载用户信息
            WQNetTool.shareTool.loadUserInfo(self.account!, finishedCallBack: { (success, failure) -> () in
                //确定字典数据正常
                guard let dict = success as? [String: AnyObject] else {
                    let error:NSError = NSError(domain: "加载用户信息返回的数据不是字典", code: -1002, userInfo: nil)
                    finishedCallBack(success: nil, failure: error)
                    return
                }
                
                // 返回的数据正常，将用户信息进一步存
                self.account!.screen_name = dict["screen_name"] as? String
                self.account!.avatar_large = dict["avatar_large"] as? String
                //归档存储用户信息
                NSKeyedArchiver.archiveRootObject(self.account!, toFile: self.accountPath)
                //返回回调
                finishedCallBack(success: self.account!, failure: nil)
                
            })
            
        }
        
    }

}